import axios from "axios";

import {ElMessage} from 'element-plus';

const baseURL = 'http://localhost:10520';
const instance = axios.create({baseURL});
import {useTokenStore, supplierTokenStore, isLoginStore} from "@/store/tokenStore.js";
import router from "@/router/index.js";
//添加请求拦截器
instance.interceptors.request.use(
    (config) => {
        const tokenStore = useTokenStore();
        const supplierStore = supplierTokenStore();
        //在请求头中添加token
        if (tokenStore.token && !supplierStore.supplierToken) {
            config.headers.Authorization = tokenStore.token;
        } else if (!tokenStore.token && supplierStore.supplierToken) {
            config.headers.Authorization = supplierStore.supplierToken;
        }
        return config;
    },
    (err) => {
        // 请求错误的回调
        return Promise.reject(err);
    }
)
//添加响应拦截器
instance.interceptors.response.use(
    result => {
        if (result.data.success === false) {
            ElMessage({
                showClose: true,
                message: result.data.errorMsg ? result.data.errorMsg : '服务异常',
                type: 'error',
            })
            return Promise.reject(result.data);
        }
        ElMessage({
            showClose: true,
            message: result.data.message ? result.data.message : '操作成功',
            type: 'success',
        })
        return result.data.data;
    },
    err => {
        console.log(err)
        if (err.status === 401) {
            //token过期
            const tokenStore = useTokenStore();
            tokenStore.clearToken();
            supplierTokenStore().clearSupplierToken()
            isLoginStore().resetLogin(false)
            ElMessage({
                showClose: true,
                message: '登录过期，请重新登录',
                type: 'error',
            })
            router.push('/');
        } else {
            ElMessage({
                showClose: true,
                message: '服务异常',
                type: 'error',
            })
            return Promise.reject(err);//异步的状态转化成失败的状态
        }
    }
)
export default instance